# from wo.goeasy import test_go
from flask import Blueprint, jsonify, request
from models.entity.task import Task
import json
from datetime import datetime

import requests
import json

from utils.result import result

server_url = 'https://rest-hangzhou.goeasy.io/publish/'

mod = Blueprint("core_task", __name__, url_prefix="/core/task", template_folder="templates",
                static_folder="static")

def test_go(send):
    # print([kwargs[k] for k in kwargs])
    # print(kwargs)
    # print('  '.join([kwargs[k] for k in kwargs]))
    # print(','.join(kwargs))
    data = {'appkey': 'BC-73a09621d2b24c2cbc33e765c2ee878a',
            'channel':'notification', 'content': send}
            # 'userId':user_id}
    url = server_url
    headers = {'Content-Type': 'application/json'}
    r = requests.post(url, data=data, headers=headers)
    # r = requests.post(url, json=data, headers=headers)
    print(type(r))
    print(r.json())


@mod.route('/', methods=['GET', 'POST'])
def task_index():
    """获取全部任务"""
    tmp = {}
    data = []
    tasks = Task.query.all()
    for item in tasks:
        data.append(item.get_dic())
    tmp['success'] = 1
    tmp['error_code'] = None
    tmp['error_msg'] = None
    tmp['data'] = data
    return jsonify(tmp)




@mod.route('/add/', methods=['GET', 'POST'])
def add_task():
    """,增加任务"""
    """
       {
        "name":"上山柴火",
        "start_time":"2016-06-22 11:26:05",
        "end_time":"2016-06-22 11:26:05",
        "task_tpl":"111",
        "task_type":"111",
        "plan_workload":1,
        "emergency_degree":1,
        "tool":"钢盔",
        "content":"mokkk",
        "user_id":1,
        "device_id":3
        
        }
    """
    tmp = {}
    data = []
    dict = json.loads(request.data.decode("utf-8"))
    if "name" not in dict:
        tmp['success'] = 0
        tmp['error_code'] = -1
        tmp['error_msg'] = "名称不能为空"
        tmp['data'] = data
        return jsonify(tmp)
    name = dict['name']
    if "start_time" not in dict:
        tmp['success'] = 0
        tmp['error_code'] = -1
        tmp['error_msg'] = "请选择开始时间"
        tmp['data'] = data
        return jsonify(tmp)
    # start_time = dict['start_time']
    start_time = dict.get('start_time', '')
    if "end_time" not in dict:
        tmp['success'] = 0
        tmp['error_code'] = -1
        tmp['error_msg'] = "请选择结束时间"
        tmp['data'] = data
        return jsonify(tmp)
    # end_time = dict['end_time']
    end_time = dict.get('end_time', '')
    # task_tpl = dict['task_tpl']
    task_tpl = dict.get('task_tpl', '')
    # emergency_degree = dict['emergency_degree']
    emergency_degree = dict.get('emergency_degree', '')
    # tool = dict['tool']
    tool = dict.get('tool', '')
    # content = dict['content']
    content = dict.get('content', '')
    # plan_workload = dict['plan_workload']
    plan_workload = dict.get('plan_workload', '')
    # task_type = dict['task_type']
    task_type = dict.get('task_type', '')
    # user_id = dict['user_id']
    user_id = dict.get('user_id', '')
    # device_id = dict['device_id']
    device_id = dict.get('device_id', '')
    task = Task()
    print('任务保存前的id', task.id)
    if len(Task.get_task_by_name(name)):
        tmp['success'] = 0
        tmp['error_code'] = -3
        tmp['error_msg'] = "名称已存在"
        tmp['data'] = data
        return jsonify(tmp)
    task.name=name
    task.task_type = task_type
    task.task_tpl=task_tpl
    task.start_time = start_time
    task.end_time = end_time
    task.emergency_degree = emergency_degree
    task.device_id = device_id
    task.user_id = user_id
    task.content = content
    task.plan_workload = plan_workload
    task.tool = tool

    if task.save():
        print('任务保存后id', task.id)
        id = task.id
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        print(111111)

        send = '任务名称: '+name+' , 开始时间: '+start_time+' , 结束时间: '+end_time+' , 内容: '+content + '?sno'
        test_go(send)
        print(222222)
        return jsonify(tmp)
    else:
        tmp['success'] = 0
        tmp['error_code'] = -3
        tmp['error_msg'] = "未知错误"
        tmp['data'] = data
        return jsonify(tmp)


@mod.route('/edit/', methods=['GET', 'POST'])
def edit_task():
    """编辑传感器类型"""
    """
        {
        "id":1,
    "name":"上山柴火",
    "start_time":"2016-06-22 11:26:05",
    "end_time":"2016-06-22 11:26:05",
    "task_tpl":"111",
    "task_type":"111",
    "plan_workload":1,
    "emergency_degree":1,
    "tool":"钢盔",
    "content":"mokkk",
    "user_id":1,
    "device_id":3
    
    }

    """
    tmp = {}
    data = []
    receive = request.data
    dict = json.loads(receive.decode("utf-8"))
    id =dict['id']
    if "name" not in dict:
        tmp['success'] = 0
        tmp['error_code'] = -1
        tmp['error_msg'] = "名称不能为空"
        tmp['data'] = data
        return jsonify(tmp)
    name = dict['name']
    if "start_time" not in dict:
        tmp['success'] = 0
        tmp['error_code'] = -1
        tmp['error_msg'] = "请选择开始时间"
        tmp['data'] = data
        return jsonify(tmp)
    start_time = dict['start_time']
    if "end_time" not in dict:
        tmp['success'] = 0
        tmp['error_code'] = -1
        tmp['error_msg'] = "请选择结束时间"
        tmp['data'] = data
        return jsonify(tmp)
    end_time = dict['end_time']
    task_tpl = dict['task_tpl']
    emergency_degree = dict['emergency_degree']
    tool = dict['tool']
    content = dict['content']
    plan_workload = dict['plan_workload']
    task_type = dict['task_type']
    user_id = dict['user_id']
    device_id = dict['device_id']
    task = Task.query.filter_by(id =id).first()
    if task.name!=name and Task.get_task_by_name(name):
        tmp['success'] = 0
        tmp['error_code'] = -3
        tmp['error_msg'] = "名称已经存在"
        tmp['data'] = data
        return jsonify(tmp)
    task.name=name
    task.task_type = task_type
    task.task_tpl=task_tpl
    task.start_time = start_time
    task.end_time = end_time
    task.emergency_degree = emergency_degree
    task.device_id = device_id
    task.user_id = user_id
    task.content = content
    task.plan_workload = plan_workload
    task.tool = tool
    if task.save():
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return jsonify(tmp)
    else:
        tmp['success'] = 0
        tmp['error_code'] = -3
        tmp['error_msg'] = "unknown error"
        tmp['data'] = data
        return jsonify(tmp)


@mod.route('/del/', methods=['GET', 'POST'])
def del_task():
    """删除传感器类型"""
    """
    {
    "id":1
    }
    """
    tmp = {}
    data = []
    receive = request.data
    dict = json.loads(receive.decode("utf-8"))
    id = dict['id']
    task = Task.query.filter_by(id=id).first()
    if not task:
        tmp['success'] = 0
        tmp['error_code'] = -1
        tmp['error_msg'] = "当前记录不存在，请重新选择"
        tmp['data'] = data
        return jsonify(tmp)
    if task.delete():
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return jsonify(tmp)
    else:
        tmp['success'] = 0
        tmp['error_code'] = -2
        tmp['error_msg'] = "未知错误"
        tmp['data'] = data
        return jsonify(tmp)


@mod.route('/get_all/', methods=['GET', 'POST'])
def get_all_task():
    """获取全部任务"""
    tmp = {}
    data = []
    tasks = Task.query.all()
    for item in tasks:
        data.append(item.get_dic())
    tmp['success'] = 1
    tmp['error_code'] = None
    tmp['error_msg'] = None
    tmp['data'] = data
    return jsonify(tmp)

@mod.route('/get_all_ing/', methods=['GET', 'POST'])
def get_all_ing_task():
    """获取进行中的任务"""
    tmp = {}
    data = []
    tasks = Task.query.filter(Task.start_time<datetime.now()).filter(
        Task.end_time>datetime.now())
    for item in tasks:
        data.append(item.get_dic())
    tmp['success'] = 1
    tmp['error_code'] = None
    tmp['error_msg'] = None
    tmp['data'] = data
    return jsonify(tmp)

# @mod.route('/get_current_task/', methods=['GET', 'POST'])
# def get_all_ing_task():
#     """获取实时任务"""
#     tmp = {}
#     data = []
#     tasks = Task.query.filter(Task.start_time<datetime.now()).filter(
#         Task.end_time>datetime.now())
#     for item in tasks:
#         data.append(item.get_dic())
#     tmp['success'] = 1
#     tmp['error_code'] = None
#     tmp['error_msg'] = None
#     tmp['data'] = data
#     return jsonify(tmp)
# test_go()

# 处理任务改变状态
@mod.route("/task_success/", methods=["GET", "POST"])
def task_success():
    #处理报警状态
    """
    {
        id : num
    }
    """
    data = []
    try:
        dict = json.loads(request.data.decode("utf-8"))
        print('dict', dict)
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    send = str(dict['name']) + '?' + str(3) + '?task'
    test_go(send)
    return result(success=1, error_code=None, error_msg=None)
    # task = Task.get_task_by_name(dict['name'])
    # print('tak', task)
    #
    # try:
    #     task.from_dict(dict)
    #     # data.append(alarm.get_dic())
    # except RuntimeError as e:
    #     return result(success=0, error_code=-2, error_msg=str(e))
    #
    # if task.save():
    #     data.append(task.get_dic())
    #     send = str(dict['name']) + '?' + str(3) + '?task'
    #     test_go(send)
    #     return result(success=1,data=data)
    # else:
    #     return result(success=0, error_code=-3, error_msg="未知错误")
